package taskmaster.util;

import taskmaster.job.Task;

import java.util.Enumeration;

/**taskmaster.util.TaskEnumeration
 * <BR><BR>
 * A simple implementation of the Enumeration interface, to avoid having to cast things to Task when using Enumerations.
 * Used in a few places; TaskBuilder, ViewTasks...
 *
 *<BR><BR>
 *Allows one extra element to be added to this enumeration.  This is done so that a Task's predecessor can be added to an enumeration of that Task's Dependancies
 *
 * TODO: use Basic Collection Classes in Java 1.5!
 */
public class TaskEnumeration implements Enumeration {
	private Enumeration e = null;
	private Task another = null;
	private boolean anotherFilled = false;

	public TaskEnumeration(Enumeration e) {
		this.e = e;
	}
	/** Implements the interface; use hasMoreTasks() instead */
	public boolean hasMoreElements() {
		return e.hasMoreElements();
	}
	/** implements the interface; use nextTask() instead */
	public Object nextElement() {
		return e.nextElement();
	}
	/** returns true as long as another call to nextTask() will return a task */
	public boolean hasMoreTasks() {
		if (e.hasMoreElements() || anotherFilled)
			return true;
		return false;
	}
	/** returns the next task in the enumeration, or an error if there are no more tasks left */
	public Task nextTask() {
		Task t = null;
		if (this.hasMoreElements()) {
			t = (Task)e.nextElement();
		} else if (anotherFilled) {
			t = another;
			anotherFilled = false;
		}
		return t;
	}
	/** add one more task to this enumeration */
	public void addAnother(Task another) throws Exception {
		if (another == null)
			return;
		if (e == null)
			throw new Exception ("taskmaster.util.TaskEnumeration.addAnother(): Can't add another Task to enumeration when base enumeration is null");
		if (this.another != null)
			throw new Exception ("taskmaster.util.TaskEnumeration.addAnother(): you have already added 1 additional Task on the end of a TaskEnumeration.  Only 1 is allowed");
		this.another = another;
		this.anotherFilled = true;
	}

    public int count(){
            int i=0;
        while(e.hasMoreElements()){
               i++;

        }
                   return i;

    }

}